package com.zephyr.vchcenter.pbcFile.util;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.zephyr.vchcenter.bean.ConfigData;
import com.zephyr.vchcenter.dao.IBaseDao;
import com.zephyr.vchcenter.helper.SpringHelper;
import com.zephyr.vchcenter.pbcFile.commons.Constance;
import com.zephyr.vchcenter.pbcFile.configBean.Dict;
import com.zephyr.vchcenter.pbcFile.exception.ConfigParseException;

/**
 * @author zhaoyunxiao
 * 
 */
public class ConfigParser {
	private static Logger log = Logger.getLogger(ConfigParser.class);

	/**
	 * @author zhaoyunxiao
	 * @throws DocumentException
	 *             ���Document
	 */
	private Document getDocument(File file) {

		SAXReader sr = new SAXReader();
		Document d = null;
		try {
			d = sr.read(file);
		} catch (Exception e) {
			log.error("ConfigParser::getDocument Error", e);
		}
		return d;
	}

	/**
	 * @author zhaoyunxiao ��ø�Ԫ��
	 */
	private Element getRoot(Document document) {

		return document.getRootElement();
	}

	/**
	 * @author zhaoyunxiao
	 */
	private Iterator<Element> getIterator(Element e) {

		return e.elementIterator();
	}

	/**
	 * @author zhaoyunxiao �����ƻ��Ԫ��
	 */
	private Element getElement(File file, String str) {
		Document doc = getDocument(file);

		log.debug(doc + "------------------->");
		Element element = null;

		Element root = getRoot(doc);
		for (Iterator<Element> it = root.elementIterator(); it.hasNext();) {
			Element elementTemp = it.next();
			if ((elementTemp.attribute("name")).getValue().equals(str)) {
				element = elementTemp;
				break;
			}
		}
		return element;
	}

	private String getItem(Element e) {
		StringBuffer sbf = new StringBuffer();
		for (Iterator<Element> it = e.elementIterator(); it.hasNext();) {
			Element element = it.next();
			if (element.getTextTrim().length() > 0) {
				sbf.append(element.getTextTrim() + ":");
			} else if (element.getText().length() == 0) {
				sbf.append("@@@@@ :");
			} else {
				sbf.append(getItem(element));
			}
		}
		return sbf.toString();
	}

	private List<String> getAnyElements(Element root, String elementName) {
		Iterator<Element> it = getIterator(root);
		List<String> list = new ArrayList<String>();
		while (it.hasNext()) {
			Element e = it.next();
			if (e.getName().equals(elementName)) {
				list.add(getItem(e));
			} else {
				list.addAll(getAnyElements(e, elementName));// 递归会不会影响效率？
			}
		}
		return list;
	}

	/*
	 * private Element getElementByName(Element e, String str) { Element element =
	 * null; for (Iterator<Element> it = e.elementIterator(); it.hasNext();) {
	 * element = it.next(); // String name=element.getName(); if
	 * ((element.getName()).equals(str)) { break; } else if
	 * (!(element.getName()).equals(str) &&
	 * !element.elementIterator().hasNext()) { continue; } else {
	 * 
	 * element = getElementByName(element, str); } }
	 * System.out.println(element.getName() + "111111111111111111"); return
	 * element; }
	 */

	private String getText(Element e) {
		return e.getTextTrim();

	}

	/*
	 * private List<String> getChildText(Element e) { List<String> list = new
	 * ArrayList<String>(); for (Iterator<Element> it = getIterator(e);
	 * it.hasNext();) { Element temp = it.next(); String textStr =
	 * getText(temp); list.add(textStr);
	 *  } return list;
	 *  }
	 */

	/**
	 * @author zhaoyunxiao
	 * @param str
	 *            �����ļ�������
	 */
	public Dict parseConfig(String subno) {
		log.debug("enter ::parseConfig");
		//System.out.println(new File("configResource/parserConfig.xml"));
		//System.out.println(this.getClass().getResource("parserConfig.xml")+"000000000000");
		//String sysURL = this.getClass().getResource("parserConfig.xml")
				//.getPath();
		// log.debug(sysURL);
		File file = new File(this.getClass().getResource("/").getPath()+"configResource/parserConfig.xml");
		
		Dict dict = new Dict();
		Element element = getElement(file, subno);
		if (element == null) {
			throw new ConfigParseException();
		}
		Element elementTemp = element.element("properties");
		Element secondElementTemp = element.element("secondProperties");
		String name = element.attributeValue("name");
		String source = element.attributeValue("class");
		dict.setName(name);
		dict.setSource(source);
		String regex = element.element("regex").attributeValue("content");
		if (element.element("regexSecond") != null) {

			String secondRegex = element.element("regexSecond").attributeValue(
					"content");
			dict.setSecondRegex(secondRegex);
		}
		dict.setRegex(regex);
		List<String> properties = new ArrayList<String>();
		List<String> secondProperties = new ArrayList<String>();
		Iterator<Element> iterator = elementTemp.elementIterator();
		while (iterator.hasNext()) {
			Element elementIt = (Element) iterator.next();
			properties.add(elementIt.getText());
		}
		dict.setProperties(properties);
		if (secondElementTemp != null) {
			Iterator<Element> secondIterator = secondElementTemp
					.elementIterator();
			while (secondIterator.hasNext()) {
				Element elementIt = (Element) secondIterator.next();
				secondProperties.add(elementIt.getText());
			}
			dict.setSecondProperties(secondProperties);
		}
		IBaseDao dao=(IBaseDao)SpringHelper.getBean("baseDao");
		ConfigData configData=new ConfigData();
		configData.setSubno(subno);
		configData.setKey("fileModle");
		List<ConfigData> list=dao.findByExample(configData);
		if(list!=null&&list.size()>0&&"2".equals(list.get(0).getValue())){
			dict.setProperties(dict.getSecondProperties());
		}
        log.debug(dict.getRegex());
		return dict;
	}
}
